<?php

namespace Caifenglei\AuthRbac\Http\Controllers;

use Caifenglei\AuthRbac\Http\Actions\PermissionAction;
use Caifenglei\AuthRbac\Http\Requests\CreatePermissionRequest;
use Caifenglei\AuthRbac\Http\Requests\UpdatePermissionRequest;
use Caifenglei\AuthRbac\Models\Permission;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\Permission\Exceptions\PermissionAlreadyExists;
use Spatie\Permission\Exceptions\RoleDoesNotExist;

class PermissionController extends Controller
{
    /**
     * @param CreatePermissionRequest $request
     * @return JsonResponse
     */
    public function store(CreatePermissionRequest $request)
    {
        $validated = $request->validated();

        try {
            $permission = PermissionAction::createPermission($validated);
            return $this->success('已成功添加权限', ['id' => $permission->getKey()]);
        } catch (PermissionAlreadyExists $e) {
            return $this->fail('权限已存在，请重新命名');
        }
    }

    /**
     * 权限列表
     * @return JsonResponse
     */
    public function index(Request $request)
    {
        $pageSize = $request->input('page_size', 15);
        $keyword = $request->input('keyword', '');
        if($keyword){
            $permissions = Permission::where('name', 'like', "%{$keyword}%")->orWhere('label', 'like', "%{$keyword}%")->paginate($pageSize);
            if($permissions->count() > 0){
                $permissions_id = $permissions->pluck('id')->toArray();
                foreach ($permissions as $perm){
                    $parent_id = $perm->parent_id;
                    if($parent_id && !in_array($parent_id, $permissions_id)){
                        $permissions_id[] = $parent_id;
                        $parent = Permission::find($parent_id);
                        $grandparent_id = $parent->parent_id;
                        if($grandparent_id && !in_array($grandparent_id, $permissions_id)){
                            $permissions_id[] = $grandparent_id;
                        }
                    }
                }
                $permissions = Permission::with(['roles' => function(BelongsToMany $query){
                        $query->select(['id', 'name', 'label'])->orderBy('sort');
                    }])->whereIn('id', $permissions_id)
                    ->orderBy('sort')
                    ->paginate($pageSize);
            }
        }else{
            $permissions = Permission::with(['roles' => function(BelongsToMany $query){
                $query->select(['id', 'name', 'label'])->orderBy('sort');
            }])->orderBy('sort')->paginate($pageSize);
        }

        return $this->success('所有权限', $this->formatPaginate($permissions));
    }

    public function show($id)
    {
        $permission = Permission::with(['roles' => function(BelongsToMany $query){
            $query->select(['id', 'name', 'label']);
        }])->find($id);
        return $this->success('权限详情', $permission->toArray());
    }

    public function update(UpdatePermissionRequest $request, $id)
    {
        $validated = $request->validated();
        $permission = Permission::find($id);
        if (!$permission) {
            return $this->fail('更新失败，权限不存在');
        }
        try {
            PermissionAction::updatePermission($permission, $validated);
        }catch (RoleDoesNotExist $e){
            return $this->fail('分配给权限的角色不存在');
        }
        return $this->success('权限更新成功');
    }

    /**
     * 删除单个权限
     * @param Request $request
     * @return JsonResponse|void
     */
    public function destroy(Request $request) {
        $id = $request->input('id');
        if(!$id){
            return $this->fail('请选择要删除的权限');
        }
        $permission = Permission::find($id);
        if(!$permission){
            return $this->fail('权限不存在');
        }
        try{
            PermissionAction::deletePermissions($permission);
            return $this->success('权限已删除');
        }catch (\Exception $e){
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 已授权的权限列表
     * @param Request $request
     * @return JsonResponse
     */
    public function granted(Request $request): JsonResponse
    {
        $user = $request->user();
        if ($user->isSuperAdmin()) {
            $menus = Permission::orderBy('sort')->get();
        } else {
            $menus = $user->getAllPermissions()->sortBy('sort', SORT_NATURAL)->values()->all();
        }
        return $this->success('菜单列表', $menus);
    }

    public function sync(Request $request)
    {
        PermissionAction::syncPermissions();
        return $this->success('权限同步成功');
    }
}
